package com.htfyun.factorytest.factorytestui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioFormat;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.WindowManager;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.VolumeUtils;
import com.htfyun.factorytest.R;
import com.htfyun.factorytest.RootApplication;
import com.htfyun.factorytest.myrecorder.RecorderThread;
import com.htfyun.factorytest.utils.DebugLog;

import java.io.File;

public class FactoryMicTestActivity extends FactoryBaseActivity {

    private IntentFilter mIntentFilter;
    private MicSpeakerReceiver mMicSpeakerReceiver;
    private MediaPlayer mediaPlayer;

    public static final String ACTION_RECORD_START = "action.record.start";
    public static final String ACTION_RECORD_STOP = "action.record.stop";
    public static final String ACTION_PLAY_START = "action.play.start";
    public static final String ACTION_PLAY_STOP = "action.play.stop";

    private static final String TEST_WAV = Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "test.wav";

    @Override
    int getLayoutId() {
        return R.layout.activity_factory_mic_test;
    }

    @Override
    protected void onPause() {
        super.onPause();
        unregisterReceiver(mMicSpeakerReceiver);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(mMicSpeakerReceiver, mIntentFilter);
    }

    @Override
    void onInitView(@Nullable Bundle savedInstanceState) {
        //设置窗体始终点亮
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        mMicSpeakerReceiver = new MicSpeakerReceiver();
        mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(ACTION_RECORD_START);
        mIntentFilter.addAction(ACTION_RECORD_STOP);
        mIntentFilter.addAction(ACTION_PLAY_START);
        mIntentFilter.addAction(ACTION_PLAY_STOP);
    }

    @Override
    void onHandleMessage(Handler handler, Message msg) {

    }

    private class MicSpeakerReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (TextUtils.isEmpty(action)) {
                return;
            }
            DebugLog.e("action = " + action);

            if (ACTION_PLAY_START.equals(action)) {
                startTestPlaySound();

            } else if (ACTION_PLAY_STOP.equals(action)) {
                stopTestPlaySound();

            } else if (ACTION_RECORD_START.equals(action)) {
                startRecord();

            } else if (ACTION_RECORD_STOP.equals(action)) {
                stopRecord();

            }

        }
    }

    private void startTestPlaySound() {
        if (mediaPlayer != null) {
            stopTestPlaySound();
        }
        try {
            VolumeUtils.setVolume(AudioManager.STREAM_MUSIC, VolumeUtils.getMaxVolume(AudioManager.STREAM_MUSIC), 0);

            File testFile = new File(TEST_WAV);
            if (testFile.exists()) {
                mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(testFile.getAbsolutePath());
                mediaPlayer.prepare();
            } else {
                mediaPlayer = MediaPlayer.create(getContext(), R.raw.spk);
            }
            mediaPlayer.setLooping(true);//这种这个后, setOnCompletionListener 不能被调用了.
            mediaPlayer.start();

        } catch (Exception e) {
            DebugLog.e("exception e = " + e.getMessage());
        }


        mediaPlayer.setOnErrorListener((mp, what, extra) -> {
            DebugLog.e("onError, what = " + what + ", extra = " + extra);
            return true;
        });

    }

    private void stopTestPlaySound() {

        if (mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();//回收资源
            mediaPlayer = null;
        }

    }

    //////////////////////
    //    Recorder
    /////////////////////
    private RecorderThread recorderThread;
    private final int SampleRateInHz = 16000;
    private static final String RECORDER_FILE_PATH = RootApplication.getContext().getExternalFilesDir(null).getAbsolutePath() + File.separator + "mic_test.pcm";

    public void startRecord() {
        startRecordTread();
    }

    private void stopRecord() {
        stopRecordThread();
    }

    private void startRecordTread() {

        if (recorderThread != null) {
            stopRecordThread();
        }

        recorderThread = new RecorderThread("es7210-", null, RECORDER_FILE_PATH);
        recorderThread.getRecorderOperator().setSampleRateInHz(SampleRateInHz);
        recorderThread.getRecorderOperator().setChannelConfig(AudioFormat.CHANNEL_IN_STEREO);
        recorderThread.getRecorderOperator().setAudioFormat(AudioFormat.ENCODING_PCM_16BIT);
        recorderThread.start();

    }

    private void stopRecordThread() {

        if (recorderThread != null) {
            recorderThread.joinThread();
            recorderThread = null;
        }
    }

}
